/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import http from '@ohos.net.http';
import router from '@system.router';
import bundle from '@ohos.bundle'
import util from '@ohos.util'
import prompt from '@system.prompt';
export default {
    data: {
        typeData: ['视频应用', '安全', '区块链', '物联网', '大数据', 'AR/VR', '游戏', '其他'],
        typeName: ["Video Application", "Safety", "Blockchain", "Internet of Things", "Big Data", "AR/VR", "Game", "Others"],
        appList0: [],
        appList1: [],
        appList2: [],
        appList3: [],
        appList4: [],
        appList5: [],
        appList6: [],
        appList7: [],
        xtoken: "",
        xsession: "",
        accessToken: "",
    },
    onInit() {
        this.get_xtoken();
    },
    onUser() {
        if (this.$app.$def.data.name == "guest") {
            router.push({
                uri: "pages/login/login",
                params: {
                    lastPage: "pages/index/index"
                }
            });
        } else {
            router.push({
                uri: "pages/userstate/userstate",
            });
        }
    },
    onDesc(appItem) {
        router.push({
            uri: "pages/description/description",
            params: {
                appItem: appItem,
            }
        })
    },
    get_xtoken() {
        let url  = this.$app.$def.data.usermgmtIP + '/v1/identity/verifycode-image'
        let httpRequest = http.createHttp();
        httpRequest.on('napi_headersReceive', (data) => {
        });
        httpRequest.request(
            url,
            {
                method: 'GET', // 可选，默认为“GET”
                header: {
                    'Content-Type': 'image/jpeg',
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                this.xtoken = data.cookies.substring(data.cookies.length-130, data.cookies.length-94);
                this.xsession = data.cookies.substring(data.cookies.length-32);
                this.get_access_token();
            } else {
                //console.info('myapp2 get_xtoken err:' + err);
                httpRequest.destroy();
            }
        }
        );
    },
    get_access_token() {
        let url = this.$app.$def.data.usermgmtIP + '/v1/accesstoken';
        let httpRequest = http.createHttp();
        httpRequest.on('headersReceive', (data) => {
        });
        let session_value = 'AUTHSERVERSESSIONID=' + this.xsession + ';';
        let cookie_value = session_value + 'XSRF-TOKEN=' + this.xtoken + ';';
        httpRequest.request(
            url,
            {
                method: 'POST', // 可选，默认为“GET”
                header: {
                    'Content-Type': 'application/json',
                    'Cookie': cookie_value,
                    'Connection': 'keep-alive',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept': '*/*',
                    'X-XSRF-TOKEN': this.xtoken
                },
                extraData:
                {
                    "userFlag": "guest",
                    "password": "guest"
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                this.accessToken = JSON.parse(data.result).accessToken;
                httpRequest.destroy();
                for (var i = 0; i < this.typeName.length; i++) {
                    this.onAppType(this.typeName[i]);
                }
            } else {
                //console.info('myapp2 get_access_token error:' + err);
                httpRequest.destroy();
            }
        }
        );

    },
    onAppType(appType) {
        //console.info("myapp2 AppType");
        // 每一个httpRequest对应一个http请求任务，不可复用
        let httpRequest = http.createHttp();
        httpRequest.on('headersReceive', (data) => {
            //console.info('header: ' + data.header);
        });
        let session_value = 'AUTHSERVERSESSIONID=' + this.xsession + ';';
        let cookie_value = session_value + 'XSRF-TOKEN=' + this.xtoken + ';';
        let url = this.$app.$def.data.appstoreIP + "/mec/appstore/v2/apps/action/query"
        httpRequest.request(
            url,
            {
                method: 'POST', // 可选，默认为“GET”
                header: {
                    'Content-Type': 'application/json',
                    'Cookie': cookie_value,
                    'Connection': 'keep-alive',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept': '*/*',
                    'X-XSRF-TOKEN': this.xtoken,
                    'accesstoken': this.accessToken
                },
                extraData: {
                    "types": [appType],
                    "showType": ["public", "inner-public"],
                    "affinity": [],
                    "industry": [],
                    "workloadType": [],
                    "userId": "",
                    "queryCtrl": {
                        "limit": 0,
                        "offset": 0,
                        "sortItem": "createTime",
                        "sortType": "desc",
                        "status": ["Published"],
                        "appName": ""
                    }
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
//                console.info('myapp2 query app code:' + data.result);
                if (appType == "Video Application") {
                    this.appList0 = JSON.parse(data.result).results;
                    for (var j = 0; j < this.appList0.length; j++) {
                        this.onDownloadIcon(this.appList0[j].packageId, j, appType);
                        this.onAppScore(this.appList0[j].appId, j, appType);
                        this.onAppComment(this.appList0[j].appId, j, appType);
                    }
                } else if (appType == "Safety") {
                    this.appList1 = JSON.parse(data.result).results;
                    for (var j = 0; j < this.appList1.length; j++) {
                        this.onDownloadIcon(this.appList1[j].packageId, j, appType);
                        this.onAppScore(this.appList1[j].appId, j, appType);
                        this.onAppComment(this.appList1[j].appId, j, appType);
                    }
                } else if (appType == "Blockchain") {
                    this.appList2 = JSON.parse(data.result).results;
                    for (var j = 0; j < this.appList2.length; j++) {
                        this.onDownloadIcon(this.appList2[j].packageId, j, appType);
                        this.onAppScore(this.appList2[j].appId, j, appType);
                        this.onAppComment(this.appList2[j].appId, j, appType);
                    }
                } else if (appType == "Internet of Things") {
                    this.appList3 = JSON.parse(data.result).results;
                    for (var j = 0; j < this.appList3.length; j++) {
                        this.onDownloadIcon(this.appList3[j].packageId, j, appType);
                        this.onAppScore(this.appList3[j].appId, j, appType);
                        this.onAppComment(this.appList3[j].appId, j, appType);
                    }
                } else if (appType == "Big Data") {
                    this.appList4 = JSON.parse(data.result).results;
                    for (var j = 0; j < this.appList4.length; j++) {
                        this.onDownloadIcon(this.appList4[j].packageId, j, appType);
                        this.onAppScore(this.appList4[j].appId, j, appType);
                        this.onAppComment(this.appList4[j].appId, j, appType);
                    }
                } else if (appType == "AR/VR") {
                    this.appList5 = JSON.parse(data.result).results;
                    for (var j = 0; j < this.appList5.length; j++) {
                        this.onDownloadIcon(this.appList5[j].packageId, j, appType);
                        this.onAppScore(this.appList5[j].appId, j, appType);
                        this.onAppComment(this.appList5[j].appId, j, appType);
                    }
                } else if (appType == "Game") {
                    this.appList6 = JSON.parse(data.result).results;
                    for (var j = 0; j < this.appList6.length; j++) {
                        this.onDownloadIcon(this.appList6[j].packageId, j, appType);
                        this.onAppScore(this.appList6[j].appId, j, appType);
                        this.onAppComment(this.appList6[j].appId, j, appType);
                    }
                } else if (appType == "Others") {
                    this.appList7 = JSON.parse(data.result).results;
                    for (var j = 0; j < this.appList7.length; j++) {
                        this.onDownloadIcon(this.appList7[j].packageId, j, appType);
                        this.onAppScore(this.appList7[j].appId, j, appType);
                        this.onAppComment(this.appList7[j].appId, j, appType);
                    }
                }
            } else {
                //console.info('myapp2 error:' + err);
                // 当该请求使用完毕时，调用destroy方法主动销毁。
                httpRequest.destroy();
            }
        }
        );
    },
    onDownloadIcon(packageId, i, appType) {
        //console.info("myapp2 onDownloadIcon");
        // 每一个httpRequest对应一个http请求任务，不可复用
        let httpRequest = http.createHttp();
        // 用于订阅http响应头，此接口会比request请求先返回。可以根据业务需要订阅此消息
        // 从API 8开始，使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
        httpRequest.on('headersReceive', (data) => {
            //console.info('header: ' + data.header);
        });
        let url = this.$app.$def.data.appstoreIP + "/mec/appstore/v1/packages/" + packageId + "/action/download-icon"
        httpRequest.request(
        // 填写http请求的url地址，可以带参数也可以不带参数。URL地址需要开发者自定义。GET请求的参数可以在extraData中指定
            url,
            {
                method: 'GET', // 可选，默认为“GET”
                // 开发者根据自身业务需要添加header字段
                header: {
                    'Content-Type': 'application/json'
                },
                // 当使用POST请求时此字段用于传递内容

                extraData: {
                    //"data": "data to send",
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                // data.result为http响应内容，可根据业务需要进行解析
                var lresult = new Uint8Array(data.result);
                var that = new util.Base64();
                var finresult = that.encodeToStringSync(lresult);
                var pic = "data:image/jpeg;base64," + finresult;
                if (appType == "Video Application") {
                    this.appList0[i].deployMode = pic;
                } else if (appType == "Safety") {
                    this.appList1[i].deployMode = pic;
                } else if (appType == "Blockchain") {
                    this.appList2[i].deployMode = pic;
                } else if (appType == "Internet of Things") {
                    this.appList3[i].deployMode = pic;
                } else if (appType == "Big Data") {
                    this.appList4[i].deployMode = pic;
                } else if (appType == "AR/VR") {
                    this.appList5[i].deployMode = pic;
                } else if (appType == "Game") {
                    this.appList6[i].deployMode = pic;
                } else if (appType == "Others") {
                    this.appList7[i].deployMode = pic;
                }
            } else {
                // 当该请求使用完毕时，调用destroy方法主动销毁。
                httpRequest.destroy();
            }
        }
        );
    },
    onAppScore(appId, i, appType) {
        // 每一个httpRequest对应一个http请求任务，不可复用
        let httpRequest = http.createHttp();
        // 用于订阅http响应头，此接口会比request请求先返回。可以根据业务需要订阅此消息
        // 从API 8开始，使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
        httpRequest.on('headersReceive', (data) => {
            //console.info('header: ' + data.header);
        });
        let url = this.$app.$def.data.appstoreIP + "/mec/appstore/v1/apps/" + appId
        httpRequest.request(
            // 填写http请求的url地址，可以带参数也可以不带参数。URL地址需要开发者自定义。GET请求的参数可以在extraData中指定
            url,
            {
                method: 'GET', // 可选，默认为“GET”
                // 开发者根据自身业务需要添加header字段
                header: {
                    'Content-Type': 'application/json',
                    'accesstoken': this.accessToken
                },
                // 当使用POST请求时此字段用于传递内容

                extraData: {
                    //"data": "data to send",
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                //console.info('myapp2 request onAppScore code:' + data.responseCode);
                // data.header为http响应头，可根据业务需要进行解析
                if (appType == "Video Application") {
                    this.appList0[i].atpTestTaskId = JSON.parse(data.result).score;
                } else if (appType == "Safety") {
                    this.appList1[i].atpTestTaskId = JSON.parse(data.result).score;
                } else if (appType == "Blockchain") {
                    this.appList2[i].atpTestTaskId = JSON.parse(data.result).score;
                } else if (appType == "Internet of Things") {
                    this.appList3[i].atpTestTaskId = JSON.parse(data.result).score;
                } else if (appType == "Big Data") {
                    this.appList4[i].atpTestTaskId = JSON.parse(data.result).score;
                } else if (appType == "AR/VR") {
                    this.appList5[i].atpTestTaskId = JSON.parse(data.result).score;
                } else if (appType == "Game") {
                    this.appList6[i].atpTestTaskId = JSON.parse(data.result).score;
                } else if (appType == "Others") {
                    this.appList7[i].atpTestTaskId = JSON.parse(data.result).score;
                }
            } else {
                //console.info('myapp2 error:' + err);
                // 当该请求使用完毕时，调用destroy方法主动销毁。
                httpRequest.destroy();
            }
        }
        );
    },
    onAppComment(appId, i, appType) {
        console.info("myapp onAppComment");
        // 每一个httpRequest对应一个http请求任务，不可复用
        let httpRequest = http.createHttp();
        // 用于订阅http响应头，此接口会比request请求先返回。可以根据业务需要订阅此消息
        // 从API 8开始，使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
        httpRequest.on('headersReceive', (data) => {
            console.info('header: ' + data.header);
        });
        let url = this.$app.$def.data.appstoreIP + "/mec/appstore/v2/apps/" + appId + "/comments?limit=100&offset=0";
        httpRequest.request(
            // 填写http请求的url地址，可以带参数也可以不带参数。URL地址需要开发者自定义。GET请求的参数可以在extraData中指定
            url,
            {
                method: 'GET', // 可选，默认为“GET”
                // 开发者根据自身业务需要添加header字段
                header: {
                    'Content-Type': 'application/json',
                    'accesstoken': this.accessToken
                },
                // 当使用POST请求时此字段用于传递内容

                extraData: {
                    //"data": "data to send",
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                // data.result为http响应内容，可根据业务需要进行解析
                 console.info('myapp total Result:' + data.result);
                 console.info('myapp request total code:' + data.responseCode);
                // data.header为http响应头，可根据业务需要进行解析
                 if (appType == "Video Application") {
                     this.appList0[i].contact = JSON.parse(data.result).total;
                 } else if (appType == "Safety") {
                     this.appList1[i].contact = JSON.parse(data.result).total;
                 } else if (appType == "Blockchain") {
                     this.appList2[i].contact = JSON.parse(data.result).total;
                 } else if (appType == "Internet of Things") {
                     this.appList3[i].contact = JSON.parse(data.result).total;
                 } else if (appType == "Big Data") {
                     this.appList4[i].contact = JSON.parse(data.result).total;
                 } else if (appType == "AR/VR") {
                     this.appList5[i].contact = JSON.parse(data.result).total;
                 } else if (appType == "Game") {
                     this.appList6[i].contact = JSON.parse(data.result).total;
                 } else if (appType == "Others") {
                     this.appList7[i].contact = JSON.parse(data.result).total;
                 }
            } else {
                console.info('myapp error:' + err);
                // 当该请求使用完毕时，调用destroy方法主动销毁。
                httpRequest.destroy();
            }
        }
        );
    },
    onMore(appList, index) {
        router.push({
            uri: "pages/moreapp/moreapp",
            params: {
                appList: appList,
                index: index
            }
        });
    }
}
